############
# station.py
# 8/19/08
############

import MySQLdb, sys, random, time, select
from toggle import *
from time import localtime, strftime
from simplemail import *
from RFIDTCM import *
import sets

def toHex(s):
    lst = []
    for ch in s:
        hv = hex(ord(ch)).replace('0x', '')
        if len(hv) == 1:
            hv = '0'+hv
        lst.append(hv)
    
    return reduce(lambda x,y:x+y, lst)

def history(cursor, u_id, bike_id, status):
	cursor.execute("select count(*) from History")
        h_num = cursor.fetchall()[0][0] + 1
        cursor.execute("insert into History (id, user_id, bike_id, checked_date, checked_h, checked_m, checked_s, type, location) values ('" + str(h_num) + "', '" + str(u_id) + "', '" + str(bike_id) + strftime("', '%Y-%m-%d', '%H', '%M', '%S', '", localtime()) + status + "','" + str(location) + "')")
        cursor.execute("select * from User where id = " + str(u_id))
        user_info =  cursor.fetchall()[0]
        if status == "CHECK_IN":
                mail_admin2("\n" +str(user_info[1])+ " " + str(user_info[2]) + " checked in bike " + str(bike_id) + " at time " + time.strftime("%H:%M:%S, %Y-%m-%d") + " from station " + str(location) + ".", "Bike Check In")
		mail_user("\nHello " + str(user_info[1])+ " " + str(user_info[2]) + ", \n\nThis email was sent to let you know that you checked in bike " + str(bike_id) + " at time " + time.strftime("%H:%M:%S, %Y-%m-%d") + " from station " + str(location) + "." + "\nThank you for using Centenary's BikeSwipe Program. \n\nSincerely,\nThe BikeSwipe Team" , "Bike Check In", user_info[3] + "@centenary.edu")
        elif status == "CHEC_OUT":
                mail_admin2("\n" + str(user_info[1]) + " " + str(user_info[2]) + " checked out bike " + str(bike_id) + " at time " + time.strftime("%H:%M:%S, %Y-%m-%d") + " from station " + str(location) + ".", "Bike Check Out")
		mail_user("\nHello " + str(user_info[1])+ " " + str(user_info[2]) + ", \n\nThis email was sent to let you know that you checked out bike " + str(bike_id) + " at time " + time.strftime("%H:%M:%S, %Y-%m-%d") + " from station " + str(location) + "." + "\n Thank you for using Centenary's BikeSwipe Program. \n\nSincerely,\nThe BikeSwipe Team" , "Bike Check Out", user_info[3] + "@centenary.edu")
       
def get_connection():
	print "Before Global"
	global conn
	print "Before Conn"
	conn = MySQLdb.connect (host = my_host,
                       		user = "bikeswipe",
                       		passwd = "Tbontb?76",
                       		db = "bikeswipe_db")
	print "Before return Conn"
	return conn.cursor()
	


bike_list = ["a","b", "c", "d", "e", "f", "g", "h"]

global conn
conn = None

quit = False

my_host = "cs.centenary.edu"

u_id = 0

bike_id = -1
# This assigns the bike_id of -1 for the History database table
box = False

print sys.argv[1]
if len(sys.argv) < 2:
    print "No Console Number"
    sys.exit(-1)

location = int(sys.argv[1])

cursor = get_connection()
cursor.execute("SELECT id from Bike where location =" + sys.argv[1])
current_bikes = cursor.fetchall()
c_b2 = []
for c in current_bikes:
	c_b2.append(c[0])
current_bikes = sets.Set(c_b2)
cursor.close()
conn.close()
print current_bikes

try:
    while (not quit):
	myin, myout, myerr = select.select([sys.stdin],[],[],0.5)
	if (is_box_open()):
		print "Box Open. Can't issue key"
		box = True
	elif (not is_box_open() and box):
		box = False
		print "Box Closed"
		found_tags = []
		for x in range(1,9):
    			"Tell a tag to shut up"
    			#Transmitter OFF
    			ser.write('\xf7')
    			sleep(0.5)
    			#Transmitter ON
    			ser.write('\xf8')
    			sleep(0.5)
			ser.write('\x05\x03\x03\x26\x1B\x61')
			for y in range(1,9):
				if x != y:
					Stay_Quiet(y)
			ser.flushInput()
			ser.flushOutput()
			ser.write('\x06\x0C\x27\x01\x00\x2A\x50')
    			s = ser.read(12)
			print toHex(s)
			if toHex(s)[:4] == "0000":
				found_tags.append(long(x))
		print found_tags
		found_tags = sets.Set(found_tags)
		# Comparing current_bikes and found_tags
		checkout_bikes = current_bikes.difference(found_tags)
		returned_bikes = found_tags.difference(current_bikes)
		current_bikes = found_tags
		print returned_bikes
		print checkout_bikes
		ser.flushInput()
		ser.flushOutput()
		cursor = get_connection()
		for i in checkout_bikes:
			bike_id = int(i)
			SQLSTout = """UPDATE Bike SET location = -1, user_id = %s, %s Where id = '%s'""" % (u_id, strftime("checked_date = '%Y-%m-%d', checked_h = '%H', checked_m = '%M', checked_s = '%S'", localtime()), bike_id)
			print SQLSTout
			cursor.execute(SQLSTout)
			print "bike " + str(bike_id) + " checked out to " + str(u_id)
                        history(cursor, u_id, bike_id, "CHEC_OUT")
		for i in returned_bikes:
			bike_id = int(i)
			SQLST = """UPDATE Bike SET location = %s, user_id = %s, %s Where id = '%s'""" % (location, "000010", strftime("checked_date = '%Y-%m-%d', checked_h = '%H', checked_m = '%M', checked_s = '%S'", localtime()), bike_id)
			print SQLST
			cursor.execute(SQLST)
			print "bike" + str(bike_id) + "checked in"
                        history(cursor, u_id, bike_id, "CHECK_IN")
			
		cursor.execute("""select id, user_id, rfid from Bike""")
		print cursor.fetchall()
		history(cursor, u_id, -1, "BOX_CLOS")
		cursor.close()
		conn.close()

	elif (len(myin) > 0):
                incoming_text = sys.stdin.readline()
		if (incoming_text != ""):
                    print "This is the incoming text: "
                    print incoming_text
                    if sys.argv[1] == str(0):
		        u_id = incoming_text[3:10].strip()
                    else:
			for c in incoming_text:
			    print ord(c), ",",
			print
                        u_id = incoming_text[11:17]
                        
                    try:
                        print "This is the u_id"
                        print u_id
                        print len(u_id)
		    	if (int(u_id[4]) != 0 and (int(u_id[0]) + int(u_id[1]) - int(u_id[2]) * int(u_id[3]) / int(u_id[4])) %7 == int(u_id[5])):
                            print "Valid Number"
                            cursor = get_connection()
                            print "Cursor got connection"
                            cursor.execute("select id from User where id =" + u_id)
                            if (len(cursor.fetchall()) != 0):
			    	print "Valid User"
			    	open_box()
			    	print "Box Opened"
                            	history(cursor, u_id, bike_id, "BOX_OPEN")
				box = True
                                raw_input("Hit Enter to Continue")
			    else:
			        print "Invalid User"
                                history(cursor, u_id, bike_id, "INVALUSR")
			    cursor.close()
			    conn.close()
		        else:
		            print "Invalid Number"
                            cursor = get_connection()
                            history(cursor, u_id, bike_id, "INVALNUM")
                    except (ValueError, IndexError):
                        print "Invalid Input"
                else:
                    print "Something Strange Happened"
	else:
		print "Waiting for users"
except KeyboardInterrupt:
    print "Thank You for using Centenary Bikeswipe! Donations can be made in Wright 104"
		

	
